<template>
  <div>
    <TopFilter ref="form" :list="topFilterList" labelWidth="110" :cols="3" :collapse="false" @filterChange="changeHandler" />
    <FilterTable
      ref="table"
      columnsRef="jzyCardType"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      selectionType="single"
      :onRowSelectChange="rowSelectHandle"
      :onColumnsChange="columns => (this.columns = columns)"
      :isExportExcel="true"
      exportFileName="打印结算单导出.xlsx"
    >
      <!-- <template slot="moreActions">
        <span @click="removeRecordHandle">删除数据</span>
      </template>-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-printer" @click="exportPdf">无纸化打印</el-button>
        <el-button size="small" type="primary" icon="el-icon-printer" :loading="printBtnLoading" @click="printBalanceClick">打印结算单</el-button>
        <AjaxButton v-if="showQualificationPrintBtn" size="small" type="primary" icon="el-icon-printer" :click="handlePrintQualification">打印竣工合格证</AjaxButton>

        <el-button size="small" type="primary" icon="el-icon-printer" @click="printCard">打印出门证</el-button>
        <el-button size="small" type="primary" icon="el-icon-printer" :loading="tablePrintBtnLoading" @click="handlePrintTable">打印列表</el-button>
      </template>
    </FilterTable>
    <BasePrint ref="printVehicled" :data="this.printExitCardList" template="templateExitCard" />

    <!-- 打印结算单 -->
    <BasePrint ref="print" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplate" />
    <!-- 结算单江苏 -->
    <BasePrint ref="printJS" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateJS" />
    <!-- 结算单上海 -->
    <BasePrint ref="printSH" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateSH" />
    <!-- 备件销售结算单 -->
    <BasePrint ref="partSalePrint" :data="partSalePrintData" template="repair/repairReception/feesSettlement/partSalerOrderFinalTemplate" />
    <!-- 打印table列表数据 -->
    <BasePrint ref="tableDataPrint" :data="tablePrintData" template="repair/repairReception/printfinance/printMainTable" />
    <!-- 打印出厂合格证 -->
    <BasePrint ref="qualificationPrint" :data="qualificationPrintData" template="repair/repairReception/feesSettlement/qualificationTemplate" />
  </div>
</template>

<script>
// 数据字典/按钮权限
import moment from 'moment';
import QRcode from 'qrcode';
import { dictionary } from '@/utils/dictMixin';
import { jsonToHump } from '@/utils/index';
import {
  findUrlQR,
  queryPrintData,
  getAdviceLabour,
  getAdvicePart,
  getRepairTypes,
  getLabourWorkData,
  getPartWorkData,
  queryRoLabourByRoNO,
  queryRoRepairPartByRoNO,
  queryRoAddItemByRoNO,
  queryCompanyInforById,
  pdfBalance,
  queryPrintLabourDataList,
  queryPrintRepartPartDataList,
  queryPartSaleOrderPrintData,
  queryOrderSuggestLabour,
  queryQualificationInfoByRono
} from '@/api/repair/repairReception/feesSettlement';
import { getSystemDefault } from '@/api/repair/repairReception/customer';

import { queryVipInfoByRono, queryVipInfoByBillNo } from '@/api/finance/repairFinance/cancelFinance';
import { getCompanyId } from '@/assets/js/auth';
import { getUser } from '@/assets/js/auth';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { getPrintBalanceList, getAllUser } from '@/api/repair/repairReception/printfinance';
import { findAllRepair } from '@/api/repair/basicParameters';
import dictCode from '@/utils/dictCode';
import { getUserId } from '@/assets/js/auth';

export default {
  name: 'CardType',
  components: {},
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.selectedRow = null;
    this.editData = {};
    return {
      printVehicledShow: false,
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getPrintBalanceList,
      printList: {}, // 结算单数据
      printExitCardList: {}, // 出门证数据
      userList: [], // 人员信息表
      fetchParams: { xhrAbort: true },
      actions: { visible: false, type: '', title: '' }, // 弹出面板的相关信息
      companyRes: {},
      printBtnLoading: false, // 打印按钮loading状态
      partSalePrintData: {}, // 备件结算单打印数据
      tablePrintData: {}, // 打印table列表数据
      tablePrintBtnLoading: false, // 打印table列表按钮loading状态
      allUserList: [], // 用户列表(翻译用)
      wechatCodeHost: 'https://miniprogram.faw-vw.com/appraise/code',
      showQualificationPrintBtn: false, // 是否显示竣工合格证打印按钮
      qualificationPrintData: {} // 合格证打印数据
    };
  },
  created() {
    this.getAllUser();
    this.queryServiceAdvisor();
    this.queryPirntBtnParams();
  },
  mounted() {
    this.initDate();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '委托书编号',
          fieldName: 'roNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '备件销售单号',
          fieldName: 'salesPartNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请输入...'
        },
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          fieldName: 'ERDAT_START|ERDAT_END',
          initialValue: [
            moment(new Date())
              .subtract('months', 6)
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ]
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '是否结清',
          fieldName: 'PAY_OFF',
          itemList: this.createDictList(1004)
        },
        {
          type: 'SELECT',
          label: '是否欠款',
          fieldName: 'ARR_BALANCE',
          itemList: this.createDictList(1004)
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          fieldName: 'showTax',
          itemList: [{ text: '显示税额', value: '1' }],
          change: this.checkBoxHandle
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          fieldName: 'printVIP',
          itemList: [{ text: '打印会员信息', value: '1' }],
          change: this.checkBoxHandle
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '接车服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          filter: true,
          filterType: 'input',
          dictItems: []
        },
        {
          title: '委托书编号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'OWNER_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '牌照号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工单状态',
          dataIndex: 'RO_STATUS',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'checkbox',
          filterItems: [...this.createDictList(8049)],
          dictItems: [...this.createDictList(8049), ...this.createDictList(1004)],
          render: props => {
            return <span>{props.row.RO_STATUS == 10041001 || props.row.RO_STATUS == 10041002 ? '' : this.createDictText(props.row.RO_STATUS, 8049)}</span>;
          }
        },
        {
          title: '结算状态',
          dataIndex: 'BALANCE_STATUS',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '是否欠款结算',
          dataIndex: 'ARR_BALANCE',
          sorter: true,
          filter: true,
          filterType: this.createDictList(1004),
          dictItems: this.createDictList(1004)
        },
        // {
        //   title: '收银状态',
        //   dataIndex: 'PAY_OFF',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   render: props => {
        //     return <span>{props.row.PAY_OFF === 10041001 ? '结清' : '欠款'}</span>;
        //   }
        // },
        {
          title: '结算日期',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd',
          filterType: 'date-range'
        },
        {
          title: '合计金额',
          dataIndex: 'RECEIVEABLE_TOTAL_AMOUNT',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '合计优惠',
          dataIndex: 'PREFERENTIAL_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算员',
          dataIndex: 'BALANCE_HANDLER',
          sorter: true,
          filter: true,
          filterType: 'input',
          dictItems: []
        },
        // {
        //   title: '包工方式',
        //   dataIndex: 'ZHBQK',
        //   sorter: true,
        //   filter: true,
        //   precision: 2,
        //   filterType: 'number'
        // },
        {
          title: '应收工时费',
          dataIndex: 'RECEIVEABLE_LABOUR_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '实收工时费',
          dataIndex: 'REAL_LABOUR_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '应收材料费',
          dataIndex: 'RECEIVEABLE_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '实收材料费',
          dataIndex: 'REAL_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '操作人',
          dataIndex: 'CREATED_BY',
          sorter: true,
          filter: true,
          filterType: 'input',
          dictItems: []
        }
      ];
    },
    initDate() {
      let date = [
        moment(new Date())
          .subtract('months', 6)
          .format('YYYY-MM-DD') + ' 00:00:00',
        moment().format('YYYY-MM-DD') + ' 23:59:59'
      ];
      let val = {
        ERDAT_START: date[0],
        ERDAT_END: date[1]
      };
      this.fetchParams = { ...val };
    },
    printBalanceClick() {
      if (this.selectedRow === null) {
        this.$notify.warning({ title: '提示信息', message: '请选择打印对象' });
      } else {
        // this.checkPrint();
        console.log(this.selectedRow);
        if (this.selectedRow.RO_NO) {
          this.getBalancePrintData();
        } else {
          this.getPartSaleOrderPrintData();
        }
      }
    },
    // 工单结算单打印
    async getBalancePrintData() {
      let totalData = '', // 整体数据
        companyData = '', // 根据公司id获取公司信息
        repairProjectData = '', // 维修项目数据
        repairMaterialData = '', // 维修材料数据
        additionData = '', // 附加项目数据
        adviceData = '', // 获取维修建议数据
        showTax = false, // 是否打印税金
        printVIP = false, // 是否打印会员
        qrCodeData = '', // 付款二维码
        serverManagerName = '', // 服务总监
        remarkParams = [], // 说明
        wechatQrCode = '', // 小程序二维码
        settlementMode = '', // 是否启用一步收款
        vipCardData = {};
      // 如果打印税额的数组长度不为0 判定需要打印税额
      if (this.topFilterList.find(item => item.fieldName === 'showTax').initialValue.length > 0) {
        showTax = true;
      }
      // 如果打印会员的数组长度不为0 判定需要打印会员
      if (this.topFilterList.find(item => item.fieldName === 'printVIP').initialValue.length > 0) {
        printVIP = true;
      }

      this.printBtnLoading = true;

      // 获取当前经销商数据与客户数据
      try {
        let balanceNumber = this.selectedRow.BALANCE_NO == undefined ? 1 : this.selectedRow.BALANCE_NO;
        totalData = await queryPrintData(this.selectedRow.RO_NO, balanceNumber);
      } catch (err) {
        console.log(err, '获取打印经销商与客户数据失败');
      }

      // 获取公司信息
      try {
        companyData = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
      } catch (err) {
        console.log(err, '获取公司信息失败');
      }

      // 获取服务总监
      try {
        let params = { role: dictCode.SERVE_MAJORDOM };
        serverManagerName = (await searchRoleByCode(params)).data[0].employeeName;
      } catch (err) {
        console.log('获取服务总监失败', err);
      }

      // 维修项目  queryRoLabourByRoNO,  row.RO_NO
      try {
        repairProjectData = await queryPrintLabourDataList(this.selectedRow.RO_NO);
      } catch (err) {
        console.log(err, '获取维修项目打印数据失败');
      }

      // 维修材料 queryRoRepairPartByRoNO, row.RO_NO
      if (this.selectedRow.BALANCE_NO) {
        try {
          // repairMaterialData = await queryRoRepairPartByRoNO(this.selectedRow.RO_NO);
          repairMaterialData = await queryPrintRepartPartDataList(this.selectedRow.BALANCE_NO);
        } catch (err) {
          console.log(err, '获取维修材料打印数据失败');
        }
      }

      // 附加项目 queryRoAddItemByRoNO,  row.RO_NO\
      try {
        additionData = await queryRoAddItemByRoNO(this.selectedRow.RO_NO);
      } catch (err) {
        console.log(err, '获取附加项目打印数据失败');
      }

      // 获取维修建议
      try {
        // adviceData = await getAdviceLabour(this.selectedRow.VIN, this.selectedRow.RO_NO);
        adviceData = await queryOrderSuggestLabour(this.selectedRow.RO_NO || '');
      } catch (err) {
        console.log(err, '获取维修建议失败');
      }

      // 获取收费二维码
      let ownerNo = '';
      // if (this.printData.type === 'roNo') {
      ownerNo = this.selectedRow.OWNER_NO;

      // } else {
      //   ownerNo = this.printData.CUSTOMER_CODE;
      // }
      // 如果是维修业务打印直接获取工单信息里面的车主编号
      // if (this.printData.isBusinessPrint === '10041001') {
      //  ownerNo = res.data.roInfo.OWNER_NO;
      // }
      try {
        qrCodeData = await this.getPayQrcode(this.selectedRow.BALANCE_NO, ownerNo);
      } catch (err) {
        console.log(err, '获取二维码失败');
      }

      // 获取结算单说明 8107 - 8112
      try {
        let remarkArr = ['8107', '8108', '8109', '8110', '8111', '8112'];
        let remarkRes = (await findAllRepair()).data;
        let arr = [];
        for (let item in remarkRes) {
          if (remarkArr.includes(item)) {
            arr.push(remarkRes[item]);
          }
        }
        remarkParams = arr;
        settlementMode = remarkRes['9402'];
      } catch (err) {
        console.log(err, '获取结算说明失败');
      }

      // 如需打印会员信息获取会员信息
      if (printVIP) {
        let type = 1; // 预留--暂时只有工单 2 3分别为 销售单2，装饰单3 销售单号：salesPartNo，结算单号：balanceNo 装饰单号：billNo hxj 2020/2/24
        let fetchapi = type == 1 ? queryVipInfoByRono : queryVipInfoByBillNo;
        let params =
          type == 1
            ? {
                roNo: this.selectedRow.RO_NO
              }
            : {
                orderType: row.SALES_PART_NO ? 2 : 3,
                salesPartNo: row.SALES_PART_NO || '',
                billNo: row.BILL_NO || '',
                balanceNo: row.BALANCE_NO
              };

        try {
          let res = await fetchapi(params);
          if (res.resultCode == 200 && res.data.result == true) {
            vipCardData = res.data.ReturnMemberInfo;
          }
        } catch (err) {
          console.log('获取会员信息失败');
        }
      }
      this.printBtnLoading = false;

      let payTypeCode = ''; // 付款方式
      let arrBalance = false; // 是否欠收结算
      try {
        // 结算日期单独处理
        totalData && (totalData.data.roInfo.COMPLETE_TIME = totalData.data.roInfo.COMPLETE_TIME ? totalData.data.roInfo.COMPLETE_TIME.split('T')[0] : '');
        totalData && (totalData.data.roInfo.BALANCE_TIME = totalData.data.roInfo.BALANCE_TIME ? totalData.data.roInfo.BALANCE_TIME.split(' ')[0] : '');
        // 翻译部分数据
        totalData && (totalData.data.roInfo.TRACE_TIME = this.createDictText(totalData.data.roInfo.TRACE_TIME, '8029'));
        totalData.data.roInfo.SERVICE_ADVISOR = this.userList[totalData.data.roInfo.SERVICE_ADVISOR] || '';
        totalData.data.roInfo.INSPECTOR = this.userList[totalData.data.roInfo.INSPECTOR] || totalData.data.roInfo.INSPECTOR;
        repairProjectData.data.map(item => (item.LABOUR_PROPERTY = this.createDictText(item.LABOUR_PROPERTY, '8104')));
        payTypeCode = totalData.data.roInfo.PAY_TYPE_CODE;
        arrBalance = totalData.data.roInfo.ARR_BALANCE == '10041001';
        // 结算人
        let createBy = totalData.data.roInfo.CREATED_BY;
        totalData.data.roInfo.CREATED_BY_NAME = this.userList[createBy];
      } catch (err) {
        console.log('翻译数据失败', err);
      }

      // 生成小程序二维码
      try {
        let repairCode = totalData.data.roInfo.REPAIR_TYPE_CODE;
        let dataUrl =
          repairCode == 0 || repairCode == 2
            ? `${this.wechatCodeHost}?dealerCode=${companyData.data.ascCode}&vin=${totalData.data.roInfo.VIN}&roType=${repairCode}&roNo=${totalData.data.roInfo.RO_NO}&startDate=${totalData.data.roInfo.RO_CREATE_DATE}&serviceConsultant=${totalData.data.roInfo.SERVICE_ADVISOR}`
            : '';
        wechatQrCode = await QRcode.toDataURL(dataUrl, {
          margin: 0
        });
      } catch (err) {
        console.log(err, '生成卓越二维码失败');
      }

      this.printList = {
        ...totalData.data,
        repairProjectData: repairProjectData.data,
        repairMaterialData: repairMaterialData.data,
        additionData: additionData.data,
        adviceData: adviceData.data,
        payQrCode: qrCodeData,
        showTax: showTax,
        printVIP: printVIP,
        companyData: companyData.data || {},
        remarkParams,
        vipCardData,
        serverManagerName,
        payTypeCode,
        arrBalance,
        wechatQrCode,
        settlementMode
      };

      if (companyData.data && companyData.data.province == 320000) {
        // 江苏
        this.$refs.printJS.EXCUTE_PRINT();
      } else if (companyData.data && companyData.data.province == 310000) {
        // 上海
        this.$refs.printSH.EXCUTE_PRINT();
      } else {
        this.$refs.print.EXCUTE_PRINT();
      }
    },
    // 销售单结算单打印
    // 获取备件销售结算单打印
    async getPartSaleOrderPrintData() {
      this.printBtnLoading = true;
      // selectedRow
      let orderData = '', // 订单信息
        companyData = '', // 公司信息
        vipCardData = '', // 会员卡信息
        qrCodeData = ''; // 付款二维码

      // 获取主要打印数据 SALES_PART_NO BALANCE_NO
      try {
        orderData = await queryPartSaleOrderPrintData({
          salesPartNo: this.selectedRow.SALES_PART_NO,
          balanceNo: this.selectedRow.BALANCE_NO || ''
        });
      } catch (err) {
        console.log(err, '获取备件销售结算单打印数据失败');
      }
      // 获取公司信息
      try {
        companyData = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
      } catch (err) {
        console.log(err, '获取公司信息失败');
      }
      // 获取会员卡信息
      try {
        let vipres = await queryVipInfoByBillNo({
          orderType: 2,
          salesPartNo: this.selectedRow.SALES_PART_NO,
          balanceNo: this.selectedRow.BALANCE_NO || ''
        });
        if (vipres.resultCode == 200 && vipres.data.result) {
          vipCardData = vipres.data.ReturnMemberInfo;
        }
      } catch (err) {
        console.log('获取会员卡信息失败', err);
      }
      try {
        this.selectedRow.CUSTOMER_CODE = this.selectedRow.OWNER_NO;
        this.selectedRow.CUSTOMER_NAME = this.selectedRow.OWNER_NAME;
      } catch (err) {
        console.log(err, '赋值修界面据报错');
      }

      // 获取收费二维码
      let ownerNo = this.selectedRow.CUSTOMER_CODE;
      // 如果是维修业务打印直接获取工单信息里面的车主编号
      if (this.selectedRow.isBusinessPrint === '10041001') {
        ownerNo = res.data.roInfo.OWNER_NO;
      }
      try {
        qrCodeData = await this.getPayQrcode(this.selectedRow.BALANCE_NO, ownerNo);
      } catch (err) {
        console.log(err, '获取二维码失败');
      }
      this.printBtnLoading = false;

      // 单独处理部分数据
      if (orderData.data.payObj) {
        orderData.data.payObj[0].PAY_TYPE_NAME = this.createDictText(orderData.data.payObj[0].PAY_TYPE_CODE, '8044');
      }

      let printData = {
        ...orderData.data,
        basePrintData: this.selectedRow,
        companyData: companyData.data || {},
        vipCardData: vipCardData,
        payQrCode: qrCodeData
      };
      this.partSalePrintData = printData;
      this.$refs.partSalePrint.EXCUTE_PRINT();
    },
    // 打印出门证
    async printCard() {
      let companyData = ''; // 根据公司id获取公司信息
      if (this.selectedRow === null) {
        this.$notify.warning({ title: '提示信息', message: '请选择打印对象' });
        return;
      } else {
        this.printVehicledShow = true;
        //  let balanceTime = moment(this.selectedRow.BALANCE_TIME).format('YYYY-MM-DD');
        // let roCreateDate = moment(this.selectedRow.RO_CREATE_DATE).format('YYYY-MM-DD');
        let balanceHandler = this.selectedRow.BALANCE_HANDLER;
        // let users = this.columns.find(x => x.dataIndex === 'BALANCE_HANDLER').editItems;
        // users.forEach(x => {
        //   if (x.value === balanceHandler) {
        //     balanceHandler = x.text;
        //   }
        // });
        // 获取公司信息
        try {
          companyData = await queryCompanyInforById({
            owenrCode: getCompanyId()
          });

          console.log(companyData);
        } catch (err) {
          console.log(err, '获取公司信息失败');
        }

        this.printExitCardList = {
          license: this.selectedRow.LICENSE,
          ownerName: this.selectedRow.OWNER_NAME,
          balanceHandler: getUser(),
          companyData: companyData.data || {}
        };
        this.$nextTick(() => {
          this.$refs.printVehicled.EXCUTE_PRINT();
        });
      }
    },

    // 获取二维码改造
    async getPayQrcode(BALANCE_NO, OWNER_NO) {
      // 获取收费对象
      // let object = this.formList.find(item => item.fieldName === 'object').initialValue;
      // 判断收费对象是否与结算单收费对象一致一致则查询二维码
      // console.log(object, OWNER_NO, BALANCE_NO, BALANCE_NO);
      if (BALANCE_NO !== '' && BALANCE_NO !== undefined) {
        const res = await findUrlQR(OWNER_NO, BALANCE_NO);
        console.log(res, 'res');

        if (res.resultCode === 200) {
          let url = res.data.GOTO_URL;
          this.GOTO_URL = url;
          if (url !== undefined && url !== '') {
            const setUrl = await QRcode.toDataURL(url);
            return setUrl;
          }
        } else {
          throw new Error(res);
        }
      } else {
        throw new Error('收费对象与结算单收费对象不符');
      }
    },
    async exportPdf() {
      if (this.selectedRow === null) {
        this.$notify.warning({ title: '提示信息', message: '请选择生成对象' });
      } else if (this.selectedRow.RO_NO) {
        let params = {
          roNo: this.selectedRow.RO_NO,
          balanceNo: this.selectedRow.BALANCE_NO,
          vin: this.selectedRow.VIN,
          payObjectCode: this.selectedRow.OWNER_NO,
          isVIP: null
        };
        if (this.topFilterList.find(item => item.fieldName === 'printVIP').initialValue.length > 0) {
          params.isVIP = 10041001;
        }
        let res = await pdfBalance(params);
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '生成成功' });
        }
      }
    },
    async getAllUser() {
      const res = await getAllUser();
      console.log('操作员、录入人', res);
      res.data.map(e => {
        this.userList[e.userId] = e.employeeName;
      });
      let alluserList = res.data.map(item => ({ text: item.employeeName, value: item.userId }));
      this.columns.find(item => item.dataIndex == 'SERVICE_ADVISOR').dictItems = alluserList;
      this.columns.find(item => item.dataIndex == 'BALANCE_HANDLER').dictItems = alluserList;
      this.columns.find(item => item.dataIndex == 'CREATED_BY').dictItems = alluserList;
      this.allUserList = alluserList;
      // this.topFilterList.find(item => item.fieldName === 'inputer').itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
    },
    changeHandler(val) {
      val.ERDAT_START = val.ERDAT_START ? val.ERDAT_START.split(' ')[0] + ' 00:00:00' : '';
      val.ERDAT_END = val.ERDAT_END ? val.ERDAT_END.split(' ')[0] + ' 23:59:59' : '';
      console.log(val, 'val');
      this.fetchParams = { ...val };
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows[0];
    },

    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },

    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    },
    // 获取服务顾问
    async queryServiceAdvisor() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      let serviceAdvisorList = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
      this.topFilterList.find(item => item.fieldName == 'serviceAdvisor').itemList = serviceAdvisorList;
      let loginUserId = getUserId() + '';
      console.log(loginUserId, serviceAdvisorList, '服务顾问及当前用户信息');
      if (serviceAdvisorList.find(item => item.value == loginUserId)) {
        this.topFilterList.find(item => item.fieldName == 'serviceAdvisor').initialValue = loginUserId;
      }
    },
    // 打印列表数据
    async handlePrintTable() {
      let formData = await this.$refs.form.GET_FORM_DATA();
      try {
        this.tablePrintBtnLoading = true;
        let res = await this.fetchApi(Object.assign(formData[1], { isPrint: true }));
        if (res.resultCode == 200 && res.data.length) {
          // 翻译部分数据
          let userList = this.columns.find(item => item.dataIndex == 'SERVICE_ADVISOR').dictItems;
          res.data.map(item => {
            // item.PAY_OFF = item.PAY_OFF == 10041001 ? '结清' : '欠款';
            item.PAY_OFF = item.BALANCE_STATUS;
            item.SERVICE_ADVISOR = userList.find(item2 => item2.value == item.SERVICE_ADVISOR) ? userList.find(item2 => item2.value == item.SERVICE_ADVISOR).text : item.SERVICE_ADVISOR;
          });
          this.tablePrintData.dataList = res.data;
          this.$refs.tableDataPrint.EXCUTE_PRINT();
        }
      } catch (err) {
        console.log(err, '获取结算单打印数据失败');
      } finally {
        this.tablePrintBtnLoading = false;
      }
    },
    // 点击打印合格证按钮
    async handlePrintQualification() {
      if (this.selectedRow.RO_NO) {
        await this.printQualificationFun(this.selectedRow.RO_NO);
      } else {
        this.$notify.warning({ title: '提示信息', message: '请选择一条数据' });
      }
    },
    // 打印合格证函数
    async printQualificationFun(roNo) {
      let dealerInfo = {},
        roInfo = {};
      // 获取经销商信息
      try {
        dealerInfo =
          (
            await queryCompanyInforById({
              owenrCode: getCompanyId()
            })
          ).data || '';
      } catch (err) {
        console.log(err, '获取经销商信息失败');
      }
      // 获取工单信息
      try {
        let roRes = await queryQualificationInfoByRono({
          roNo
        });
        if (roRes.resultCode == 200 && roRes.data.length) {
          roInfo = roRes.data[0];
        }
      } catch (err) {
        console.log(err, '获取工单信息失败');
      }
      // 手动处理部分数据
      try {
        roInfo.RO_NO = roNo;
        roInfo.INSPECTOR_NAME = this.allUserList.find(x => x.value == roInfo.INSPECTOR) ? this.allUserList.find(x => x.value == roInfo.INSPECTOR).text : '';
      } catch (err) {
        console.log(err, '手动翻译数据失败');
      }
      this.qualificationPrintData = {
        roInfo,
        dealerInfo
      };
      this.$refs.qualificationPrint.EXCUTE_PRINT();
    },
    // 查询合格证按钮服务参数
    async queryPirntBtnParams() {
      let res = await getSystemDefault({ itemCode: 9405 });
      if (res.resultCode == 200) {
        res.data == '10041001' && (this.showQualificationPrintBtn = true);
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
